package com.yh.csx.bsf.core.util;

import com.yh.csx.bsf.core.base.BsfException;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @author: chejiangyi
 * @version: 2019-07-28 11:08
 **/
public class ExceptionUtils {
    public static String trace2String(Throwable t){
        if(t== null)
        {    return "";}
        try
        {
            try(StringWriter sw = new StringWriter()) {
                try(PrintWriter pw = new PrintWriter(sw, true)) {
                    t.printStackTrace(pw);
                    return sw.getBuffer().toString();
                }
            }
        }
        catch (Exception exp){
            throw new BsfException(exp);
        }
    }
    public static String trace2String(StackTraceElement[] stackTraceElements)
    {
        StringBuilder sb = new StringBuilder();
        for(StackTraceElement stackTraceElemen : stackTraceElements)
        {
            sb.append(stackTraceElemen.toString()+"\n");
        }
        return sb.toString();
    }

    private static String lineSeparator() {
        return System.getProperty("line.separator");
    }

    public static String getFullMessage(Throwable e) {
        if (e == null) {
            return "";
        }
        String message = "【详细错误】" + lineSeparator() + getDetailMessage(e) + lineSeparator() + "【堆栈打印】" + lineSeparator() + getFullStackTrace(e);
        return message;
    }

    public static String getFullStackTrace(Throwable e) {
        if (e == null) {
            return "";
        }
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            // 将出错的栈信息输出到printWriter中
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                }
            }
            if (pw != null) {
                pw.close();
            }
        }
        return sw.toString();
    }

    public static String getDetailMessage(Throwable ex) {
        if (ex == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        while (ex != null) {
            sb.append("【" + ex.getClass().getName() + "】→" + StringUtils.nullToEmpty(ex.getMessage()) + lineSeparator());
            ex = ex.getCause();
        }
        return sb.toString();
    }
    public static void ignoreException(Runnable runnable,boolean isPrintInfo){
        try{
            runnable.run();
        }catch(Exception e){
            if(!isPrintInfo){
                LogUtils.error(ExceptionUtils.class,getFullStackTrace(e));
            }
        }
    }
    public static void ignoreException(Runnable runnable){
        ignoreException(runnable,false);
    }
}
